<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="900"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    @close="closeDialog(false)"
  >
    <el-form ref="addOrEditFormRef" v-loading="loading" :model="formData" :rules="rules" label-width="170" size="">
      <!-- 添加保证金账户 -->
      <el-row v-if="dialogAddOrEdit.type == 1" justify="start" class="d_left">
        <el-col :span="12" class="">
          <el-form-item label="选择缴存账户" prop="guaranteeAccountName">
            <el-input v-model="formData.guaranteeAccountName" disabled placeholder="请选择" />
            <el-button type="primary" plain style="position: absolute; right: -10px" @click="handleSelectAccount"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="归属人社" prop="rsName">
            <el-input v-model="formData.rsName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="工资保证金开户银行" prop="bankName">
            <el-input v-model="formData.bankName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="">
          <el-form-item label="工资保证金银行账号" prop="bankNo">
            <el-input v-model="formData.bankNo" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体名称" prop="paymentName">
            <el-input v-model="formData.paymentName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体统一社会信用代码" prop="paymentCode">
            <el-input v-model="formData.paymentCode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="工资保证金应缴金额" prop="payable">
            <money-input v-model="formData.payable" disabled unit="元" />
            <!-- <el-input v-model="formData.payable" disabled placeholder="自动关联" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="已缴纳金额" prop="paid">
            <money-input v-model="formData.paid" unit="元" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="差异化缴存金额" prop="difference">
            <money-input v-model="formData.difference" disabled unit="元" />
            <!-- <el-input v-model="formData.difference" disabled placeholder="自动关联" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴存起始日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传保证金凭证" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 添加工程担保公司 -->
      <el-row v-if="dialogAddOrEdit.type == 2" justify="start" class="d_left">
        <el-col :span="12" class="">
          <el-form-item label="选择工程担保公司" prop="guaranteeAccountName">
            <el-input v-model="formData.guaranteeAccountName" disabled placeholder="请选择" />
            <el-button type="primary" plain style="position: absolute; right: -10px" @click="handleSelectAccount"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="工程担保公司信用代码" prop="socialcreditcode">
            <el-input v-model="formData.socialcreditcode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="担保公司负责人姓名" prop="superintendent">
            <el-input v-model="formData.superintendent" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="">
          <el-form-item label="担保公司负责人电话" prop="superintendentMobile">
            <el-input v-model="formData.superintendentMobile" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体名称" prop="rsName">
            <el-input v-model="formData.paymentName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体统一社会信用代码" prop="rsName">
            <el-input v-model="formData.paymentCode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="工程担保公司保函函号" prop="guaranteeLetterNo">
            <el-input v-model="formData.guaranteeLetterNo" placeholder="请输入工程担保公司保函函号" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="工程担保公司担保金额" prop="paid">
            <money-input v-model="formData.paid" unit="元" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="工程担保公司保函有效起始日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="工程担保公司保函有效终止日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传担保函凭证" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 添加工程保证保险 -->
      <el-row v-if="dialogAddOrEdit.type == 3" justify="start" class="d_left">
        <el-col :span="12" class="">
          <el-form-item label="选择保险公司名称" prop="guaranteeAccountName">
            <el-input v-model="formData.guaranteeAccountName" disabled placeholder="请选择" />
            <el-button type="primary" plain style="position: absolute; right: -10px" @click="handleSelectAccount"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="保险公司信用代码" prop="socialcreditcode">
            <el-input v-model="formData.socialcreditcode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="保险公司负责人姓名" prop="superintendent">
            <el-input v-model="formData.superintendent" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="">
          <el-form-item label="保险公司负责人电话" prop="superintendentMobile">
            <el-input v-model="formData.superintendentMobile" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体名称" prop="rsName">
            <el-input v-model="formData.paymentName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体统一社会信用代码" prop="rsName">
            <el-input v-model="formData.paymentCode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="保险单号" prop="guaranteeLetterNo">
            <el-input v-model="formData.guaranteeLetterNo" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="保单金额" prop="paid">
            <money-input v-model="formData.paid" unit="元" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="保险有效起始日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="保险有效终止日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传保险凭证" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 添加银行保函 -->
      <el-row v-if="dialogAddOrEdit.type == 4" justify="start" class="d_left">
        <el-col :span="12" class="">
          <el-form-item label="选择担保银行名称" prop="guaranteeAccountName">
            <el-input v-model="formData.guaranteeAccountName" disabled placeholder="请选择" />
            <el-button type="primary" plain style="position: absolute; right: -10px" @click="handleSelectAccount"
              >选择</el-button
            >
          </el-form-item>
        </el-col>

        <el-col :span="12" class="">
          <el-form-item label="缴纳主体名称" prop="paymentName">
            <el-input v-model="formData.paymentName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体统一社会信用代码" prop="paymentCode">
            <el-input v-model="formData.paymentCode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="银行保函函号" prop="guaranteeLetterNo">
            <el-input v-model="formData.guaranteeLetterNo" placeholder="请输入银行保函函号" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="银行保函担保金额" prop="payable">
            <money-input v-model="formData.payable" unit="元" disabled />
            <!-- <el-input v-model="formData.payable" disabled placeholder="自动关联" /> -->
          </el-form-item>
        </el-col>

        <el-col :span="12" class="">
          <el-form-item label="已缴纳金额" prop="paid">
            <money-input v-model="formData.paid" unit="元"></money-input>
            <!-- <el-input v-model="formData.paid" type="number" placeholder="请输入缴纳金额" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="差异化缴存金额" prop="difference">
            <money-input v-model="formData.difference" disabled unit="元" />
            <!-- <el-input v-model="formData.difference" disabled placeholder="自动关联" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="银行保函有效起始日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="银行保函有效终止日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传银行保函凭证" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <select-guarantee-account :dialog-select="dialogAccount" @select-send-close="sendClose"></select-guarantee-account>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ProjectGuaranteePaymentEditForm } from "@/api/guarantee/types";
import MoneyInput from "@/components/MoneyInput/index.vue";
import SelectGuaranteeAccount from "@/views/common/SelectGuaranteeAccount/index.vue";
import { getDicts } from "@/store/modules/dict";

import {
  CreateProjectGuaranteePayment,
  UpdateProjectGuaranteePayment,
  GetProjectGuaranteePayment,
} from "@/api/guarantee/index";
import { FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";

//上传地址
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);
//上传文件列表
const fileList = ref<UploadUserFile[]>([]);

const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "创建保证金账户",
      footBtn: "核实账户信息",
      id: 0,
      type: 1,
    }),
  },
});

const { dialogAddOrEdit } = toRefs(props);

const dialogAccount = ref({
  visible: false,
  type: undefined,
});

const emit = defineEmits(["sendClose"]);

const loading = ref(false);
const formData = reactive<ProjectGuaranteePaymentEditForm>({});
const addOrEditFormRef = ref(ElForm);
const depositeType = getDicts("depositeType");

//表单验证
const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传附件!"));
    return;
  } else {
    callback();
  }
};
const rules = reactive<FormRules<ProjectGuaranteePaymentEditForm>>({
  //添加保证金
  startDate: [{ required: true, message: "请选择有效起始日期", trigger: "change" }],
  endDate: [{ required: true, message: "请选择有效终止日期", trigger: "change" }],
  guaranteeAccountName: [{ required: true, message: "请选择账户", trigger: "change" }],
  //添加工程担保公司
  attachments: [
    {
      required: true,
      message: "请上传担保函凭证",
      trigger: "change",
      validator: validatorAttachment,
    },
  ],
});

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

//初始化表单
const initForm = () => {
  loading.value = true;
  dialogAccount.value.type = dialogAddOrEdit.value.type;
  let id = 0;
  if (dialogAddOrEdit.value.id) {
    id = dialogAddOrEdit.value.id;
  }
  GetProjectGuaranteePayment(id)
    .then((res) => {
      Object.assign(formData, res.data);
      if (res.data.attachments) {
        let list = Array<any>();
        res.data.attachments.forEach((item: any) => {
          list.push({
            name: item.attachmentName,
            url: item.attachmentName,
            status: "success",
            uid: item.attachmentId,
          });
        });
        fileList.value = list;
      }
    })
    .finally(() => {
      loading.value = false;
    });
  fileList.value = [];
  //初始化验证规则
  if (dialogAddOrEdit.value.type == 1) {
    rules.attachments = [
      {
        required: true,
        message: "请上传保证金凭证",
        trigger: "change",
        validator: validatorAttachment,
      },
    ];
  }
  if (dialogAddOrEdit.value.type == 2) {
    rules.attachments = [
      {
        required: true,
        message: "请上传担保函凭证",
        trigger: "change",
        validator: validatorAttachment,
      },
    ];
  }
  if (dialogAddOrEdit.value.type == 3) {
    rules.attachments = [
      {
        required: true,
        message: "请上传保险凭证",
        trigger: "change",
        validator: validatorAttachment,
      },
    ];
  }
  if (dialogAddOrEdit.value.type == 4) {
    rules.attachments = [
      {
        required: true,
        message: "请上传银行保函凭证",
        trigger: "change",
        validator: validatorAttachment,
      },
    ];
  }
};

onMounted(() => {
  initForm();
});

watch(
  () => formData.paid,
  () => {
    let difference = (formData.payable ?? 0) - (formData.paid ?? 0);
    formData.difference = difference < 0 ? 0 - difference : difference;
  }
);

const handleSelectAccount = function () {
  dialogAccount.value.visible = true;
  dialogAccount.value.type = dialogAddOrEdit.value.type;
};

const sendClose = function (info: any) {
  dialogAccount.value.visible = false;
  if (info) {
    formData.guaranteeAccountId = info.id;
    formData.guaranteeAccountName = info.name;
    formData.bankName = info.bankName;
    formData.bankNo = info.bankNo;
    formData.rsName = info.rsName;
    formData.superintendent = info.superintendent;
    formData.superintendentMobile = info.superintendentMobile;
    formData.socialcreditcode = info.socialcreditcode;
  }
};

/**
 * 关闭弹窗
 */
function closeDialog(query: boolean, data?: any) {
  emit("sendClose", query, data);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.id = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (fileList.value.length > 0) {
        let uplist = new Array<any>();
        fileList.value.forEach((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              uplist.push({ attachmentId: item.response.data });
            } else {
              uplist.push({ attachmentId: item.uid });
            }
          }
        });
        formData.attachments = uplist;
      } else {
        formData.attachments = [];
      }
      if (dialogAddOrEdit.value.id) {
        UpdateProjectGuaranteePayment(formData)
          .then((res) => {
            if (res.success) {
              closeDialog(true);
            } else {
            }
          })
          .finally(() => (loading.value = false));
        return;
      }
      formData.id = undefined;
      CreateProjectGuaranteePayment(formData)
        .then((res) => {
          if (res.success) {
            closeDialog(true);
          } else {
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}
</script>

<style lang="scss" scoped>
.d_left {
  margin-left: 10px;
}
:deep(.el-form-item) {
  flex-wrap: wrap;
}
.dialog_footer {
  // display: flex;
  // justify-content: center;
}

:deep(.el-input) {
  width: 80%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
